﻿
using com.youzu.got.protocol;
using OWL.Rendering.HRP;
using ShaderVariantCollector;
using System;
using System.Collections.Generic;
using com.yoozoo.gta.Common;
using Gameplay.RTS.Editor;
using Neonagee.LocalPreferences;
using NodeCanvas.Tasks.Actions;
using Unity.Collections;
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using WorldMap;
using WorldMapBase.Tile.Pool;
using Yoozoo.Core.Common;
using Yoozoo.HRP.Runtime;

namespace Yoozoo.Gameplay.RTS
{
    [CustomEditor(typeof(ChildDataEditor))]
    public class ChildDataEditorInspector : UnityEditor.Editor
    {
        private ChildBehaviourNativeData childData;

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
            //if (childData == null)
            {
                childData = SquareDataManager.Instance.childNativeData;
            }

            //if (childData != null)
            {
                var strs = GetDataString(childData, (target as ChildDataEditor).index);
                for (int i = 0; i < strs.Count; i++)
                {
                    GUILayout.BeginHorizontal();
                    GUILayout.TextField(strs[i]);
                    GUILayout.EndHorizontal();
                }
            }
        }

        public static List<string> GetDataString<T>(T data, int index)
        {
            List<string> strs = new List<string>();
            var classType = typeof(T);
            var properties = classType.GetFields();
            for (int i = 0; i < properties.Length; i++)
            {
                var type = properties[i].FieldType;
                if (type == typeof(int))
                {

                }
                else
                {
                    var name = properties[i].Name;
                    var str = string.Empty;
                    str += name;
                    str += " = ";
                    if (type == typeof(NativeArray<int>))
                    {
                        var value = (NativeArray<int>) properties[i].GetValue(data);
                        str += value[index];
                    }
                    else if (type == typeof(NativeArray<uint>))
                    {
                        var value = (NativeArray<uint>) properties[i].GetValue(data);
                        str += value[index];
                    }
                    else if (type == typeof(NativeArray<float>))
                    {
                        var value = (NativeArray<float>) properties[i].GetValue(data);
                        str += value[index];
                    }
                    else if (type == typeof(NativeArray<float3>))
                    {
                        var value = (NativeArray<float3>) properties[i].GetValue(data);
                        str += value[index];
                    }
                    else if (type == typeof(NativeArray<bool>))
                    {
                        var value = (NativeArray<bool>) properties[i].GetValue(data);
                        str += value[index];
                    }
                    else if (type == typeof(NativeArray<ChildToSpriteData>))
                    {
                        var value = (NativeArray<ChildToSpriteData>) properties[i].GetValue(data);
                        str += ("visible " + value[index].visible);
                        str += "\n";
                        str += ("scale " + value[index].spriteOriginScale);
                        str += "\n";
                        str += ("alpha " + value[index].alpha);
                    }

                    strs.Add(str);
                }

            }

            return strs;
        }

        [CustomEditor(typeof(SquareDataEditor))]
        public class SquareDataEditorInspector : UnityEditor.Editor
        {
            private MarchSquareNativeData marchData;

            private string customLifeTime;
            public override void OnInspectorGUI()
            {
                base.OnInspectorGUI();
                customLifeTime = GUILayout.TextField(customLifeTime);
                if (float.TryParse(customLifeTime,out var time))
                {
                    SquareDataManager.CustomLifeTime = time;
                }
                else
                {
                    SquareDataManager.CustomLifeTime = 0;
                }
                
                //if (marchData == null)
                {
                    marchData = SquareDataManager.Instance.marchNativeData;
                }

                
                //if (marchData != null)
                {
                    var strs = GetDataString(marchData, (target as SquareDataEditor).index);
                    for (int i = 0; i < strs.Count; i++)
                    {
                        GUILayout.BeginHorizontal();
                        GUILayout.TextField(strs[i]);
                        GUILayout.EndHorizontal();
                    }
                }
            }

            [MenuItem("GTATools/GamePlay/RTS/显示所有小兵调试", false, 0)]
            public static void ShowAllChildren()
            {
                SquareDataManager.Instance.ShowAllChildrenSphere();
            }
            
            [MenuItem("GTATools/GamePlay/RTS/显示隐藏所有方阵的圈", false, 0)]
            public static void ShowAllSquareCircle()
            {
                ArmyManager.Instance.MarchManager.ShowAllSquareCircle();
            }
            
            [MenuItem("GTATools/GamePlay/RTS/开启关闭小兵debug", false, 0)]
            public static void StartDebug()
            {
                if (SquareDataManager.isDebug)
                {
                    SquareDataManager.Instance.EndDebug();
                }
                else
                {
                    SquareDataManager.Instance.StartDebug();
                }
            }

            [MenuItem("GTATools/GamePlay/RTS/开启单元测试", false, 0)]
            public static void StartUnitTest()
            {
                RTSUnitTest.Enable = true;
                var rtsMono = FindObjectOfType<RTSMono>();
                if (rtsMono != null)
                {
                    var test = rtsMono.gameObject.GetOrAddComponent<RTSUnitTest>();
                    test.StartUnitTest();
                }
            }
            
            [MenuItem("GTATools/GamePlay/RTS/开启关闭简略模式", false, 0)]
            public static void StartSimpleMode()
            {
                RTSQualityHelper.ChangeSimpleMode(!RTSQualityHelper.IsSimpleMode,true);
            }
            
            
            [MenuItem("GTATools/GamePlay/RTS/显示对象池使用情况", false, 0)]
            public static void ShowPoolNum()
            {
                PoolCollectionManager.GetInstance("PoolCollectionManager").Log();
            }
            
                
            [MenuItem("GTATools/GamePlay/RTS/切换为登录进沙盘", false, 0)]
            private static void SwitchToLoginSandbox()
            {
                LocalPrefs.SetInt("LoginSandbox",1);
            }
    
            [MenuItem("GTATools/GamePlay/RTS/切换为登录进内城", false, 0)]
            private static void SwitchToLoginInnerCity()
            {
                LocalPrefs.SetInt("LoginSandbox",0);
            }

            [MenuItem("GTATools/GamePlay/RTS/夹击测试", false, 0)]
            private static void BesiegeDebug()
            {
                MarchBesiegeManager.isDebug = !MarchBesiegeManager.isDebug;
            }
            
            private static List<string> lowLevelBlackList = new List<string>()
            {
                "GGame/HRP/Charater/Fur"
            };

            // 不需要导出变体的Shader
            private static List<string> blackList = new List<string>
            {
                // Utils
                "Hidden/Universal Render Pipeline/Blit",
                "Hidden/Universal Render Pipeline/CopyDepth",
                "Hidden/Universal Render Pipeline/FallbackError",
                "Hidden/Universal Render Pipeline/Sampling",
                "Hidden/Universal Render Pipeline/ScreenSpaceShadows",

                // PostProcessing
                "Hidden/Universal Render Pipeline/Bloom",
                "Hidden/Universal Render Pipeline/BokehDepthOfField",
                "Hidden/Universal Render Pipeline/CameraMotionBlur",
                "Hidden/Universal Render Pipeline/FinalPost",
                "Hidden/Universal Render Pipeline/GaussianDepthOfField",
                "Hidden/Universal Render Pipeline/LutBuilderHdr",
                "Hidden/Universal Render Pipeline/LutBuilderLdr",
                "Hidden/Universal Render Pipeline/PaniniProjection",
                "Hidden/Universal Render Pipeline/Stop NaN",
                "Hidden/Universal Render Pipeline/SubpixelMorphologicalAntialiasing",
                "Hidden/Universal Render Pipeline/UberPost",
                
                // HRP PostProcessing
                "HRP/DualFilteringBlur",
                "HRP/PostProcessing/HHeightFog",
                "HRP/PostProcessing/HLightShaft",
                "HRP/HPlaneReflection",
                "HRP/PostProcessing/HRadialBlur",
                "HRP/PostProcessing/HSSR",
                "HRP/PostProcessing/HStroke",
                "HRP/PostProcessing/HTiltShiftBlurDOF",
                "HRP/PostProcessing/HUberPost",
                
                // HRP PPShader
                "GGame/HRP/PP/SSAO",
                "GGame/HRP/PP/AreaBlur",

                // Built-in
                "Unlit/Transparent",

                // UI
                "UI/TextDefault",
            };

            private static List<string> shaderNames = new List<string>
            {
                "PveVariantCollection",
                "LoadingVariantCollection",
                "HangingVariantCollection",
                "GuideHangingVariantCollection",
                "CityVariantCollection",
                "WorldVariantCollection",
                "BankVariantCollection"
            };

            private static Dictionary<string, List<string>> keywords = new Dictionary<string, List<string>>
            {
                ["_CHARACTER_GRAPHIC"] = new List<string>
                {
                    CharacterGraphicLevel._CHARACTER_GRAPHIC_LOW.ToString(),
                    CharacterGraphicLevel._CHARACTER_GRAPHIC_LOW.ToString(),
                    CharacterGraphicLevel._CHARACTER_GRAPHIC_MEDIUM.ToString(),
                    CharacterGraphicLevel._CHARACTER_GRAPHIC_HIGH.ToString(),
                    CharacterGraphicLevel._CHARACTER_GRAPHIC_SUPREME.ToString(),
                },
                ["_SCENE_GRAPHIC"] = new List<string>
                {
                    SceneGraphicLevel._SCENE_GRAPHIC_LOW.ToString(),
                    SceneGraphicLevel._SCENE_GRAPHIC_LOW.ToString(),
                    SceneGraphicLevel._SCENE_GRAPHIC_MEDIUM.ToString(),
                    SceneGraphicLevel._SCENE_GRAPHIC_HIGH.ToString(),
                    SceneGraphicLevel._SCENE_GRAPHIC_SUPREME.ToString(),
                }
            };
            
            [MenuItem("GTATools/性能/shader变体拆分（包含性能分级）", false, 0)]
            private static void SeparateVariant()
            {
                // 生成排除列表 (黑名单 + Always Included)
                List<string> excludeShaderList = new List<string>();
                // 黑名单
                foreach (var shaderName in blackList)
                {
                    excludeShaderList.Add(shaderName);
                }
                // Always Included Shaders
                System.Reflection.MethodInfo methodInfo = typeof(GraphicsSettings).GetMethod("GetGraphicsSettings", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
                UnityEngine.Object graphicsSettings = GraphicsSettings.GetGraphicsSettings();
                var serializedObject = new SerializedObject(graphicsSettings);
                SerializedProperty alwaysIncludedShaders = serializedObject.FindProperty("m_AlwaysIncludedShaders");
                for (int i=0; i<alwaysIncludedShaders.arraySize; ++i)
                {
                    SerializedProperty element = alwaysIncludedShaders.GetArrayElementAtIndex(i);
                    Shader shader = element.objectReferenceValue as Shader;
                    if (shader != null)
                    {
                        excludeShaderList.Add(shader.name);
                    }
                }
                
                var qualityManagerPath = "Assets/ResourcesAssets/Persistent/QualityManager.prefab";
                var qualityManagerGameObject =
                    AssetDatabase.LoadAssetAtPath<GameObject>(qualityManagerPath);
                if (qualityManagerGameObject == null)
                {
                    Debug.LogError(qualityManagerPath+"没有找到");
                    return;
                }

                var qualityManager = qualityManagerGameObject.GetComponent<QualityManager>();
                if (qualityManager == null)
                {
                    Debug.LogError("QualityManager没有找到");
                    return;
                }

                var prefab = new GameObject();
                var shaderVariantData = prefab.AddComponent<ShaderVariantData>();
                shaderVariantData.shaderVariantsName = new List<string>();
                shaderVariantData.shaderVariantsCount = new List<int>();
                for (int i = 0; i < shaderNames.Count; i++)
                {
                    //var quality = shaderQualityListener.GetAllQualitySettings();
                    //for (int j = 0; j < quality.Count; j++)
                    //int j = 0;
                    {
                        var name = shaderNames[i];// + j;
                        int count = 0;
                        var svc = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(
                            string.Format("Assets/ResourcesAssets/Shaders/{0}.shadervariants", name));
                        if (svc)
                        {
                            //先删除所有拆分了的变体
                            int index = 0;
                            while (true)
                            {
                                var p = string.Format("Assets/ResourcesAssets/Shaders/{0}_{1}.shadervariants", name,index);
                                if (!AssetDatabase.DeleteAsset(p))
                                {
                                    break;
                                }
                            }

                            var shaderVariants = ShaderVariantCollectionHelper.ExtractData(svc);

                            int idx = 0;
                            //普通变体
                            var dictionary = new Dictionary<string, List<ShaderVariantCollection.ShaderVariant>>();
                            //含有分级的变体
                            var gradeKeywordsDictionary = new List<ShaderVariantCollection.ShaderVariant>();
                            // 分析变体是否需要分级
                            foreach (var shaderVariantsPair in shaderVariants)
                            {
                                Shader shader = shaderVariantsPair.Key;

                                // 显示进度
                                idx++;
                                EditorUtility.DisplayProgressBar($"分析{name}", $"正在分析{shader.name} ({idx}/{shaderVariants.Count})...", idx/(float)shaderVariants.Count);
                                
                                // 处理黑名单 (不导出)
                                if (excludeShaderList.Contains(shader.name))
                                {
                                    continue;
                                }
                                
                                var variants = shaderVariantsPair.Value;
                                foreach (var sv in variants)
                                {
                                    try
                                    {
                                        if (!dictionary.TryGetValue(sv.shader.name,out var list))
                                        {
                                            list = new List<ShaderVariantCollection.ShaderVariant>();
                                            dictionary.Add(sv.shader.name,list);
                                        }
                                        //判断是否含有分级关键字
                                        bool hasKeyword = false;
                                        foreach (var keyword in keywords.Keys)
                                        {
                                            for (int j = 0; j < sv.keywords.Length; j++)
                                            {
                                                if (sv.keywords[j].Contains(keyword))
                                                {
                                                    hasKeyword = true;
                                                    break;
                                                }
                                            }
                                        }

                                        if (!hasKeyword)
                                        {
                                            list.Add(new ShaderVariantCollection.ShaderVariant(sv.shader,sv.passType,sv.keywords));
                                        }
                                        else
                                        {
                                            gradeKeywordsDictionary.Add(new ShaderVariantCollection.ShaderVariant(sv.shader,sv.passType,sv.keywords));
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        //Debug.LogException(e);
                                    }
                                }
                            }
                            // 隐藏进度
                            EditorUtility.ClearProgressBar();
                            
                            //先对分级的变体进行分类
                            var gradeVariantList = new List<List<ShaderVariantCollection.ShaderVariant>>();
                            for (int level = 0; level < qualityManager.adjusterSettings.Count; level++)
                            {
                                // 显示进度
                                EditorUtility.DisplayProgressBar($"导出分级变体{name}", $"正在导出level{level} ({level}/{qualityManager.adjusterSettings.Count})...", level/(float)qualityManager.adjusterSettings.Count);

                                var gradeLevel = (int) qualityManager.adjusterSettings[level].quality;
                                var vList = new List<ShaderVariantCollection.ShaderVariant>();
                                for (int j = 0; j < gradeKeywordsDictionary.Count; j++)
                                {
                                    var sv = gradeKeywordsDictionary[j];
                                    var newKeywords = new string[sv.keywords.Length];
                                    for (int jjj = 0; jjj < sv.keywords.Length; jjj++)
                                    {
                                        var keyword = sv.keywords[jjj];
                                        newKeywords[jjj] = keyword;
                                        foreach (var item in keywords)
                                        {
                                            if (keyword.Contains(item.Key))
                                            {
                                                if (item.Key == "_CHARACTER_GRAPHIC")
                                                {
                                                    newKeywords[jjj] = ((CharacterGraphicLevel)qualityManager.adjusterSettings[level].characterGraphicLevel).ToString();
                                                }
                                                else if (item.Key == "_SCENE_GRAPHIC")
                                                {
                                                    newKeywords[jjj] = ((SceneGraphicLevel)qualityManager.adjusterSettings[level].sceneGraphicLevel).ToString();
                                                }
                                            }
                                        }
                                    }

                                    try
                                    {
                                        vList.Add(new ShaderVariantCollection.ShaderVariant(sv.shader, sv.passType,
                                            newKeywords));
                                    }
                                    catch (Exception e)
                                    {
                                        /*try
                                        {
                                            vList.Add(new ShaderVariantCollection.ShaderVariant(sv.shader, sv.passType,
                                                sv.keywords));
                                        }
                                        catch (Exception exception)
                                        {
                                            Debug.LogException(e);
                                        }

                                        Debug.LogException(e);
                                        var str = string.Empty;
                                        str += "ShaderName: " + sv.shader;
                                        str += "\n";
                                        str += "PassType: " + sv.passType;
                                        str += "\n";
                                        for (int p = 0; p < newKeywords.Length; p++)
                                        {
                                            str += newKeywords[p];
                                            str += "   ";
                                        }
                                        Debug.LogError(str);*/
                                    }
                                    
                                }
                                gradeVariantList.Add(vList);
                                var collection = new ShaderVariantCollection();
                                for (int j = 0; j < vList.Count; j++)
                                {
                                    collection.Add(vList[j]);
                                }
                                var path = string.Format("Assets/ResourcesAssets/Shaders/{0}_level{1}.shadervariants", name,gradeLevel);
                                AssetDatabase.DeleteAsset(path);
                                AssetDatabase.CreateAsset(collection,path);
                            }
                            // 隐藏进度
                            EditorUtility.ClearProgressBar();

                            //规则，10个变体成为一个包，超了就分一个新包
                            idx = 0;
                            var limit = 10;
                            var l = new List<ShaderVariantCollection.ShaderVariant>();
                            var currentCollection = new ShaderVariantCollection();
                            foreach (var pair in dictionary)
                            {
                                var list = pair.Value;
                                // 显示进度
                                idx++;
                                EditorUtility.DisplayProgressBar($"导出普通变体{name}", $"正在导出{pair.Key} ({idx}/{dictionary.Count})...", idx/(float)dictionary.Count);
                                
                                if (list.Count >= limit)
                                {
                                    var collection = new ShaderVariantCollection();
                                    for (int k = 0; k < list.Count; k++)
                                    {
                                        if (!collection.Contains(list[k]))
                                        {
                                            collection.Add(list[k]);
                                        }
                                    }
                                    var path = string.Format("Assets/ResourcesAssets/Shaders/{0}_{1}.shadervariants", name,count);
                                    AssetDatabase.DeleteAsset(path);
                                    AssetDatabase.CreateAsset(collection,path);
                                    count++;
                                }
                                else
                                {
                                    for (int k = 0; k < list.Count; k++)
                                    {
                                        if (!currentCollection.Contains(list[k]))
                                        {
                                            currentCollection.Add(list[k]);
                                            l.Add(list[k]);
                                        }
                                    }

                                    if (l.Count >= limit)
                                    {
                                        var path = string.Format("Assets/ResourcesAssets/Shaders/{0}_{1}.shadervariants", name,count);
                                        AssetDatabase.DeleteAsset(path);
                                        AssetDatabase.CreateAsset(currentCollection,path);
                                        count++;
                                        currentCollection = new ShaderVariantCollection();
                                        l.Clear();
                                    }
                                }
                            }
                            // 隐藏进度
                            EditorUtility.ClearProgressBar();

                            if (currentCollection.variantCount > 0)
                            {
                                var path = string.Format("Assets/ResourcesAssets/Shaders/{0}_{1}.shadervariants", name,count);
                                AssetDatabase.DeleteAsset(path);
                                AssetDatabase.CreateAsset(currentCollection,path);
                                count++;
                            }
                        }
                        shaderVariantData.shaderVariantsName.Add(name);
                        shaderVariantData.shaderVariantsCount.Add(count);
                    }
                }

                var prefabPath = "Assets/ResourcesAssets/Prefabs/ShaderVariantData/ShaderVariantData.prefab";
                AssetDatabase.DeleteAsset(prefabPath);
                PrefabUtility.SaveAsPrefabAsset(prefab, prefabPath);
                //AssetDatabase.Refresh();
                //AssetDatabase.SaveAssets();

                EditorUtility.DisplayDialog("变体分级", "变体分级处理完成!", "确定");
            }

            //[MenuItem("GTATools/性能/shader变体性能分级", false, 0)]
            private static void CreateVariantByGrade()
            {
                var qualityManagerPath = "Assets/ResourcesAssets/Prefabs/Scene/QualityManager.prefab";
                var qualityManagerGameObject =
                    AssetDatabase.LoadAssetAtPath<GameObject>(qualityManagerPath);
                if (qualityManagerGameObject == null)
                {
                    Debug.LogError(qualityManagerPath+"没有找到");
                    return;
                }

                var qualityManager = qualityManagerGameObject.GetComponent<QualityManager>();
                if (qualityManager == null)
                {
                    Debug.LogError("QualityManager没有找到");
                    return;
                }
                
                for (int k = 0; k < shaderNames.Count; k++)
                {
                    var name = shaderNames[k];
                    var svc = AssetDatabase.LoadAssetAtPath<ShaderVariantCollection>(string.Format("Assets/ResourcesAssets/Shaders/{0}.shadervariants", name));
                    if (svc)
                    {
                        var shaderVariants = ShaderVariantCollectionHelper.ExtractData(svc);
                        //普通变体
                        var dictionary = new Dictionary<string, List<ShaderVariantCollection.ShaderVariant>>();
                        var normalVariants = new List<ShaderVariantCollection.ShaderVariant>();
                        //含有分级的变体
                        var gradeKeywordsDictionary = new List<ShaderVariantCollection.ShaderVariant>();
                        foreach (var variants in shaderVariants.Values)
                        {
                            foreach (var sv in variants)
                            {
                                try
                                {
                                    if (!dictionary.TryGetValue(sv.shader.name,out var list))
                                    {
                                        list = new List<ShaderVariantCollection.ShaderVariant>();
                                        dictionary.Add(sv.shader.name,list);
                                    }
                                    //判断是否含有分级关键字
                                    bool hasKeyword = false;
                                    foreach (var keyword in keywords.Keys)
                                    {
                                        for (int j = 0; j < sv.keywords.Length; j++)
                                        {
                                            if (sv.keywords[j].Contains(keyword))
                                            {
                                                hasKeyword = true;
                                                break;
                                            }
                                        }
                                    }

                                    if (!hasKeyword)
                                    {
                                        //list.Add(new ShaderVariantCollection.ShaderVariant(sv.shader,sv.passType,sv.keywords));
                                        normalVariants.Add(new ShaderVariantCollection.ShaderVariant(sv.shader,sv.passType,sv.keywords));
                                    }
                                    else
                                    {
                                        gradeKeywordsDictionary.Add(new ShaderVariantCollection.ShaderVariant(sv.shader,sv.passType,sv.keywords));
                                    }
                                }
                                catch (Exception e)
                                {
                                    //Debug.LogException(e);
                                }
                            }
                        }
                        var quality = qualityManager.adjusterSettings;
                        for (int i = 0; i < quality.Count; i++)
                        {
                            var gradeLevel = (int)quality[i].quality;
                            //先对分级的变体进行分类
                            var vList = new List<ShaderVariantCollection.ShaderVariant>();
                            for (int j = 0; j < gradeKeywordsDictionary.Count; j++)
                            {
                                var sv = gradeKeywordsDictionary[j];
                                var newKeywords = new string[sv.keywords.Length];
                                for (int jjj = 0; jjj < sv.keywords.Length; jjj++)
                                {
                                    var keyword = sv.keywords[jjj];
                                    newKeywords[jjj] = keyword;
                                    foreach (var item in keywords)
                                    {
                                        if (keyword.Contains(item.Key))
                                        {
                                            if (item.Key == "_CHARACTER_GRAPHIC")
                                            {
                                                newKeywords[jjj] = ((CharacterGraphicLevel)quality[i].characterGraphicLevel).ToString();
                                            }
                                            else if (item.Key == "_SCENE_GRAPHIC")
                                            {
                                                newKeywords[jjj] = ((SceneGraphicLevel)quality[i].sceneGraphicLevel).ToString();
                                            }
                                        }
                                    }
                                }

                                try
                                {
                                    vList.Add(new ShaderVariantCollection.ShaderVariant(sv.shader, sv.passType,
                                        newKeywords));
                                }
                                catch (Exception e)
                                {
                                    /*try
                                    {
                                        vList.Add(new ShaderVariantCollection.ShaderVariant(sv.shader, sv.passType,
                                            sv.keywords));
                                    }
                                    catch (Exception exception)
                                    {
                                        Debug.LogException(e);
                                    }*/

                                    /*Debug.LogException(e);
                                    var str = string.Empty;
                                    str += "ShaderName: " + sv.shader;
                                    str += "\n";
                                    str += "PassType: " + sv.passType;
                                    str += "\n";
                                    for (int p = 0; p < newKeywords.Length; p++)
                                    {
                                        str += newKeywords[p];
                                        str += "   ";
                                    }
                                    Debug.LogError(str);*/
                                }
                                
                            }
                        
                            var collection = new ShaderVariantCollection();
                            for (int j = 0; j < vList.Count; j++)
                            {
                                collection.Add(vList[j]);
                            }

                            for (int j = 0; j < normalVariants.Count; j++)
                            {
                                collection.Add(normalVariants[j]);
                            }
                            /*foreach (var list in dictionary.Values)
                            {
                                for (int j = 0; j < list.Count; j++)
                                {
                                    collection.Add(list[j]);
                                }
                            }*/
                            
                            var path = string.Format("Assets/ResourcesAssets/Shaders/{0}_{1}.shadervariants", name,gradeLevel);
                            AssetDatabase.DeleteAsset(path);
                            AssetDatabase.CreateAsset(collection,path);
                        }
                        AssetDatabase.Refresh();
                        AssetDatabase.SaveAssets();
                    }
                }
                
            }

            [MenuItem("GTATools/性能/检测碰撞体", false, 0)]
            private static void CheckCollider()
            {
                var colliders = FindObjectsOfType<Collider>();
                var camera = HCameraManager.GetBaseCamera();
                int count = 0;
                int wasteCount = 0;
                var center = BattleUtils.GetGroundPositionByScreenPosition(camera.Camera,
                    new Vector2(Screen.width / 2, Screen.height / 2));
                int validCount = 0;
                for (int i = 0; i < colliders.Length; i++)
                {
                    var screenPos = camera.Camera.WorldToScreenPoint(colliders[i].transform.position);
                    if (screenPos.x < Screen.width && screenPos.x >= 0 && screenPos.y < Screen.height &&
                        screenPos.y >= 0)
                    {
                        
                    }
                    else
                    {
                        if (colliders[i].enabled)
                        {
                            var distance = Vector3.Distance(center, colliders[i].transform.position);
                            count++;
                            if (distance > 1000)
                            {
                                Debug.LogError("碰撞体在视野外，但是还是开启的状态" + colliders[i].name + " 距离摄像机" + distance);
                                wasteCount++;
                            }
                        }
                    }

                    if (colliders[i].enabled)
                    {
                        validCount++;
                    }
                }
                Debug.LogError("当前总共碰撞体" + validCount + "个，"+"总共检测出"+wasteCount+"个碰撞体在浪费");
            }
        }

        [MenuItem("GTATools/GamePlay/RTS/检测小兵是否重复", false, 0)]
        public static void CheckChildData()
        {
            SquareDataManager.Instance.CheckChildData();
        }
        
        [MenuItem("GTATools/GamePlay/RTS/打印所有小兵对应的序列帧id", false, 0)]
        public static void PrintChildData()
        {
            SquareDataManager.Instance.PrintChildData();
        }
        
        [MenuItem("GTATools/GamePlay/RTS/奇观工具", false, 0)]
        public static void WonderTool()
        {
            EditorWindow.GetWindow<WonderEditorWindow>("奇观工具", true);
        }
        
        [MenuItem("GTATools/GamePlay/RTS竞技场/准备", false, 0)]
        public static void RtsArenaPrepare()
        {
            RtsArenaTest.Prepare();
        }
        
        [MenuItem("GTATools/GamePlay/RTS竞技场/清理", false, 0)]
        public static void RtsArenaClear()
        {
            RtsArenaTest.Clear();
        }
        
        [MenuItem("GTATools/GamePlay/RTS竞技场/协议",false,0)]

        public static void TestSendMsg()
        {
            RtsArenaTest.TestSendMsg();
        }


        private static int truckId;
        [MenuItem("GTATools/GamePlay/RTS货车/生成货车", false, 0)]
        public static void TestTruck()
        {
            var camera = WorldCameraManager.mainCamera;
            var center =
                BattleUtils.GetGroundPositionByScreenPosition(camera, new Vector2(Screen.width, Screen.height));
            SquareDataManager.Instance.CreateTruckAttacker(truckId,center,Vector3.forward,5);
            truckId++;
        }
    }
}
